import { NextFunction, Request, Response } from 'express'
import { monitorService } from '../services/monitor/service'
import logger from '../utils/logger'

export const monitorMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const start = Date.now()

  // 监听响应完成事件
  res.on('finish', () => {
    const duration = Date.now() - start
    const success = res.statusCode < 400

    // 记录请求
    monitorService.recordRequest(success)

    // 记录请求时间
    if (success) {
      logger.info(`${req.method} ${req.path} - ${res.statusCode} (${duration}ms)`)
    } else {
      logger.warn(`${req.method} ${req.path} - ${res.statusCode} (${duration}ms)`)
    }
  })

  next()
}
